package com.huiyin.ui.videoplayer;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;

import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.RequstClient;
import com.huiyin.utils.MyCustomResponseHandler;

public class VideoPlayerActivity extends Activity implements OnClickListener, OnErrorListener, OnCompletionListener, OnPreparedListener{
	
	public static final String TAG = "VideoPlayerActivity";
	
	public static final String VIDEO_SRC = "videoSrc";
	
	public static final String SPOTLOGHT_ID = "spotlightId";
	
	private VideoView adVideo;
	
	private Button  playBtn;
	
	private String videoSrc;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.videoview_item);
		
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		
		init();
		addShowViewNum();
	}
	
	//添加秀场浏览量
	private void addShowViewNum() {
		String spotlightId = getIntent().getStringExtra(SPOTLOGHT_ID);
		if(!TextUtils.isEmpty(spotlightId)) {
			RequstClient.addShowViewNum(new MyCustomResponseHandler(this) {}, spotlightId);
		}
	}

	private void init() {
		
		videoSrc = getIntent().getStringExtra(VIDEO_SRC);
		Log.d(TAG, "videoSrc = " + videoSrc);
		
		playBtn = (Button) findViewById(R.id.play_btn);
		playBtn.setOnClickListener(this);
		
		initVideo();
		setVideoSrc(videoSrc);
	}
	
	private void initVideo() {
		adVideo = (VideoView) findViewById(R.id.videoview);
		adVideo.setMediaController(new MediaController(this));
		adVideo.setOnPreparedListener(this);
		adVideo.setOnCompletionListener(this);
		adVideo.setOnErrorListener(this);
	}
	
	public void setVideoSrc(String src) {
		if(!TextUtils.isEmpty(src)) {
			adVideo.setVideoURI(Uri.parse(src));
		}
		else {
			UIHelper.showToast("播放地址不能为空");
		}
	}
	
	public VideoView getAdVideo() {
		return adVideo;
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.play_btn:
			
			if(adVideo.isPlaying()) {
				adVideo.pause();
			}
			else {
				adVideo.start();
			}
			
			break;

		default:
			break;
		}
		
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		Log.d(TAG, "onError : what = " + what + "  extra = " + extra);
		UIHelper.showToast("播放出错");
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		adVideo.start();
	}

}
